package a.b.c.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 参考：https://blog.csdn.net/kidults/article/details/98725710
 * <p>
 * 1、拉取platform.xml文件
 * adb pull system/etc/permissions/platform.xml D:/HomeWork
 * <p>
 * 2、修改文件：
 * 将
 * <permission name="android.permission.READ_EXTERNAL_STORAGE"/>
 * <permission name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 * 修改成
 * <permission name="android.permission.READ_EXTERNAL_STORAGE">
 * <group gid="media_rw"/>
 * </permission>
 * <permission name="android.permission.WRITE_EXTERNAL_STORAGE">
 * <group gid="media_rw"/>
 * </permission>
 * <p>
 * 3、上传文件
 * adb push D:/HomeWork/platform.xml system/etc/permissions/
 * create by duxl 2022/10/23
 */
public class USBUtils3 {

    private final String TAG = "USBUtils3";

    private final String mDirStethoData = "StethoData";

    public static USBUtils3 getInstance() {
        return InnerHolder.instance;
    }

    private static final class InnerHolder {
        public static USBUtils3 instance = new USBUtils3();
    }

    public USBUtils3() {
    }

    /**
     * 递归删除文件和目录（必须是空目录才能删除）
     *
     * @param f
     */
    private void deleteFile(File f) {
        if (f == null) {
            return;
        }

        if (f.isFile()) {
            f.delete();
            return;
        }

        if (f.isDirectory()) {
            // 删除目录下的子目录和文件
            for (File file : f.listFiles()) {
                deleteFile(file);
            }
            f.delete();
        }
    }

    public String read(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[512];
            int len;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            String result = new String(bos.toByteArray(), "UTF-8");
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return "读失败：" + e.getMessage();
        }
    }

    public String write(byte[] data, File toFile) {
        try {
            OutputStream os = new FileOutputStream(toFile);
            os.write(data);
            os.flush();
            os.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    /**
     * 获取目录下的文件数量
     *
     * @param dir
     * @param sum
     * @return
     */
    public int getFileCount(File dir, int sum) {
        if (dir.isDirectory()) {
            for (File file : dir.listFiles()) {
                if (file.isFile()) {
                    sum++;
                } else {
                    sum = getFileCount(file, sum);
                }
            }
        }
        return sum;
    }

    /**
     * 查找U盘路径
     *
     * @return
     */
    public String searchPath() {
        String filePath = "/proc/mounts";
        File file = new File(filePath);
        List<String> lineList = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GBK");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    if (line.contains("vfat")) {
                        lineList.add(line);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String path = null;
        if (!lineList.isEmpty()) {
            try {
                String editPath = lineList.get(lineList.size() - 1);
                int start = editPath.indexOf("/mnt");
                int end = editPath.indexOf(" vfat");
                path = editPath.substring(start, end);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.d(TAG, "path: " + path);
        return path;
    }

    private void logShow(String msg) {
        Log.d(TAG, msg);
    }
}
